package com.zzx.project.controller;

import com.zzx.project.entity.*;
import com.zzx.project.service.ArticleService;
import com.zzx.project.service.CommentService;
import com.zzx.project.service.MaximService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//文章Controller
@Controller
@RequestMapping("article")
public class ArticleController {

    @Autowired
    ArticleService articleService;
    @Autowired
    CommentService commentService;
    @Autowired
    MaximService maximService;

    //添加文章
    @RequestMapping("add")
    public String articleInfo(Article article, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        String cover = session.getAttribute("link").toString();
        article.setArticlecover(cover);
        int flag = articleService.addArticle(article, "0," + user.getUserid().toString());
        if (flag > 0) {
            Article article1 = articleService.getNewArticleByUname(user.getUsername());
            List<Tag> tags = getTagList(article1);
            model.addAttribute("tags", tags);
            model.addAttribute("article", article1);
            model.addAttribute("tip", "提交成功");
            return "main/content";
        } else {
            model.addAttribute("tip", "提交失败，请保存文本信息并联系站长进行解决");
            return "write/index";
        }
    }

    //打开文章
    @GetMapping("show/{id}")
    public String show(@PathVariable("id") String aidString, HttpServletRequest request, Model model) {
        //初始化作用域属性对象
        List<Article> randomArticleResponse = null;
        Maxim maxim = null;
        int findSupport = 0;

        //直接访问文章页时的初始化
        if (checkInit(request.getSession()) == null) {
            List<Article> randomArticle = articleService.getRandomArticle();
            randomArticleResponse = new ArrayList<>();
            for (Article article : randomArticle) {
                String[] audiences = article.getArticleaudience().split(",");
                article.setArticleaudiences(audiences.length - 1);
                randomArticleResponse.add(article);
            }
        }

        //获取每日格言
        if (request.getSession().getAttribute("maxim") == null) {
            maxim = maximService.getNewMaxim();
        }

        //用户id
        String uid;
        //没登录的情况下uid为0，即不计入本文章观众
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            uid = "0";
        } else {
            uid = null == user.getUserid() ? "0" : String.valueOf(user.getUserid());
        }

        //根据文章id获取对应的文章对象实例
        Article article = articleService.getArticleById(aidString);
        if (null == article || null == article.getArticleid()) {
            return "main/content";
        }
        List<Tag> tags = getTagList(article);//获取标签集合，具体见最下面的方法
        //通过分割字符串获取文章围观人数
        String articleAudience = article.getArticleaudience();
        String[] audiences = articleAudience.split(",");
        //通过分割字符串获取文章点赞人数
        String[] supports = article.getArticlesupport().split(",");
        for (String audience : audiences) {
            if (audience.equals(uid)) {
                article.setArticleaudiences(audiences.length - 1);
                if (user != null) {
                    String uid1 = user.getUserid().toString();
                    //判断当前登录用户有无点赞记录
                    for (String support : supports) {
                        if (support.equals(uid1)) {
                            findSupport = 1;
                        }
                    }
                    if (findSupport == 1) {
                        model.addAttribute("isSupport", 1);//该用户已点赞
                    } else {
                        model.addAttribute("isSupport", 0);//该用户未点赞
                    }
                }
                getNearArticle(article, model);
                List<Comment> comments = commentService.getCommentsByAid(article.getArticleid());
                //显示猜你喜欢的八篇文章
                model.addAttribute("recomment", articleService.getRecommend());
                model.addAttribute("tags", tags);
                model.addAttribute("comments", comments);
                model.addAttribute("article", article);
                model.addAttribute("supportCount", supports.length - 1);
                return "main/content";
            }
        }
        //如果没有观看过文章的操作，看过的话就会被上面的操作截断,以下代码与上面的代码同理
        model.addAttribute("supportCount", supports.length - 1);
        articleService.addAudience(article.getArticleaudience() + "," + uid, Integer.parseInt(aidString));
        article = articleService.getArticleById(aidString);
        audiences = articleAudience.split(",");
        article.setArticleaudiences(audiences.length - 1);
        model.addAttribute("tags", tags);
        model.addAttribute("article", article);
        if (user != null) {
            String uid1 = user.getUserid().toString();
            for (String support : supports) {
                if (support.equals(uid1)) {
                    findSupport = 1;
                }
            }
        }

        //获取猜你喜欢文章
        model.addAttribute("recomment", articleService.getRecommend());
        List<Comment> comments = commentService.getCommentsByAid(article.getArticleid());

        //作用域赋值
        request.getSession().setAttribute("randomArticle", randomArticleResponse);
        request.getSession().setAttribute("maxim", maxim);

        model.addAttribute("tags", tags);
        model.addAttribute("article", article);
        model.addAttribute("comments", comments);
        //获取点赞数-1（0不算，所以会-1）
        model.addAttribute("supportCount", supports.length - 1);
        getNearArticle(article, model);
        if (findSupport == 1) {
            model.addAttribute("isSupport", 1);
        } else {
            model.addAttribute("isSupport", 0);
        }

        return "main/content";
    }

    /**
     * <p>获取上一篇/下一篇文章.</p>
     *
     * @param model
     * @author zhouzhixin
     * @date 2021/5/8 16:35
     */
    private void getNearArticle(Article article, Model model) {
        if (article.getArticleid() != 1) {
            model.addAttribute("prevArticle", articleService.getArticleById(String.valueOf(article.getArticleid() - 1)));
        }
        if (!(article.getArticleid() >= articleService.getAllArticleCount())) {
            model.addAttribute("nextArticle", articleService.getArticleById(String.valueOf(article.getArticleid() + 1)));
        }
    }

    //点赞
    @RequestMapping("addSupport")
    @ResponseBody
    public Object addSupport(@RequestParam("uids") String uids, @RequestParam("aid") int aid, HttpSession session, Model model) {
        HashMap<String, String> map = new HashMap<>();
        User user = (User) session.getAttribute("user");
        int flag = articleService.addSupportById(uids + "," + user.getUserid(), aid);
        if (flag > 0) {
            map.put("flag", "true");
        } else {
            map.put("flag", "false");
        }
        return map;
    }

    //首页文章分页
    @RequestMapping("toPage/{page}")
    public String toPage(@PathVariable("page") int page, Model model) {
        if (page == 1) {
            return "redirect:/";
        }
        List<Article> articleLOne = articleService.getArticleForPage((page - 1) * 5);
        List<Article> list = new ArrayList<>();
        for (Article article : articleLOne) {
            int articleAudiences = article.getArticleaudience().split(",").length - 1;
            article.setArticleaudiences(articleAudiences);
            String[] tags = article.getArticletags().split(",");
            List<String> tagList = new ArrayList<>();
            for (String tag : tags) {
                tagList.add(tag);
            }
            article.setArticletaglist(tagList);
            list.add(article);
        }
        model.addAttribute("articleLOne", list);
        model.addAttribute("count", page);
        model.addAttribute("currPage", page);
        return "main/index";
    }

    //跳转相关页面
    @RequestMapping("toRelevant/{tagName}")
    public String getArticlesByTagName(@PathVariable("tagName") String tname, HttpSession session, Model model) {
        List<Article> articles = articleService.getArticlesByTagName(tname);
        model.addAttribute("relevantArticles", articles);
        model.addAttribute("columnName", tname);
        return "main/relevant";
    }

    //搜索文章
    @RequestMapping("search")
    public String searchContent(@RequestParam("searchContent") String searchContent, Model model) {
        List<Article> articles = articleService.getArticleBySearch(searchContent);
        model.addAttribute("relevantArticles", articles);
        model.addAttribute("columnName", searchContent);
        return "main/relevant";
    }

    //传入文章对象获得出他的标签集合
    public List<Tag> getTagList(Article article) {
        String tags = article.getArticletags();
        String[] tag = tags.split(",");
        List<Tag> tagList = new ArrayList<>();
        Tag tag1;
        for (String s : tag) {
            tag1 = new Tag();
            tag1.setTagname(s);
            tagList.add(tag1);
        }
        return tagList;
    }

    //检查有无初始化数据
    public String checkInit(HttpSession session) {
        if (session.getAttribute("randomArticle") == null || session.getAttribute("fiveData") == null) {
            return null;
        }
        return "has";
    }
}
